﻿using ComponentFactory.Krypton.Toolkit;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StableDiffusionTools.Forms
{
    public partial class InputDialog : KryptonForm
    {
        public string Result { get; private set; } = "";
        public bool AllowEmpty = false;
        public InputDialog(string text, string caption = "", string inputDefault = "", bool allowEmpty = false, bool selectText = true)
        {
            InitializeComponent();

            Size newSize = TextRenderer.MeasureText(text, Font, new Size(1000, 1000), TextFormatFlags.Default);
            ClientSize = new Size(Math.Max(ClientSize.Width, newSize.Width), newSize.Height + ClientSize.Height);
            kryptonLBLInputText.Text = text;
            if (!string.IsNullOrEmpty(caption))
                Text = caption;

            kryptonTBInput.Text = inputDefault;

            if (selectText)
                kryptonTBInput.SelectAll();
            else
            {
                kryptonTBInput.Select(kryptonTBInput.Text.Length, 0);
            }

            AllowEmpty = allowEmpty;

            ValidateEmpty();

            KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Escape)
                {
                    DialogResult = DialogResult.Cancel;
                }
            };

            StartPosition = FormStartPosition.CenterParent;
        }

        private void ValidateEmpty()
        {
            bool okEnabled = AllowEmpty ? true : !string.IsNullOrWhiteSpace(kryptonTBInput.Text);
            kryptonBTNOk.Enabled = okEnabled;
        }

        [Obsolete("This is not supported in this class.", true)]
        public new void Show(IWin32Window window) { }
        [Obsolete("This is not supported in this class.", true)]
        public new void Show() { }

        private void kryptonBTNOk_Click(object sender, EventArgs e)
        {
            UpdateResult();
        }

        private void kryptonTBInput_TextChanged(object sender, EventArgs e)
        {
            ValidateEmpty();
        }

        private void UpdateResult()
        {
            Result = kryptonTBInput.Text;
        }

        private void kryptonTBInput_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter && (AllowEmpty ? true : !string.IsNullOrWhiteSpace(kryptonTBInput.Text)))
            {
                e.SuppressKeyPress = true;
                UpdateResult();
                DialogResult = DialogResult.OK;
            }
        }
    }
}
